package com.lsz.flight_system.controller;

import com.lsz.flight_system.entity.Admin;
import com.lsz.flight_system.entity.UserMessage;
import com.lsz.flight_system.service.AdminService;
import com.lsz.flight_system.service.UserMessageService;
import com.lsz.flight_system.utils.PhoneCheckUtils;
import com.lsz.flight_system.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/flight")
public class LoginController {

    @Autowired
    UserMessageService userMessageService;

    @Autowired
    AdminService adminService;

    @PostMapping("/userLogin")
    public Result userLogin(@RequestBody UserMessage user, HttpSession session){
        UserMessage userMessage = userMessageService.getUserMessageByUsername(user.getUsername());
        if (userMessage == null){
            return Result.fail("用户名不存在");
        }else if (!Objects.equals(userMessage.getPassword(), user.getPassword())){
            return Result.fail("密码输入错误");
        }
        //登录信息保存到session
        session.setAttribute("USER_MESSAGE",userMessage);
        return Result.ok();
    }

    @PostMapping("/userRegister")
    public Result addUserMessage(@RequestBody UserMessage userMessage){
        if (userMessage.getUsername()==null){
            return Result.fail("请输入用户名");
        } else if (userMessage.getPassword()==null) {
            return Result.fail("请输入密码");
        } else if (userMessage.getPhone()==null) {
            return Result.fail("请输入手机号");
        }
        if (!PhoneCheckUtils.isChinaPhoneLegal(userMessage.getPhone())){
            return Result.fail("手机号格式错误");
        }
        //用户购票权限，默认为国内
        userMessage.setPermissions("国内");
        boolean message = userMessageService.registerUserMessage(userMessage);
        if (message){
            return Result.ok("注册成功");
        }else {
            return Result.fail("该用户名存在");
        }
    }

    @PostMapping("/adminLogin")
    public Result adminLogin(@RequestBody Admin admin,HttpSession session){
        Admin adminMessage = adminService.getAdminByUsername(admin.getUsername());
        if (adminMessage == null){
            return Result.fail("账号不存在");
        } else if (!Objects.equals(adminMessage.getPassword(), admin.getPassword())) {
            return Result.fail("密码输入错误");
        }
        session.setAttribute("ADMIN_MESSAGE",adminMessage);
        return Result.ok();
    }
}
